# coding:utf-8
import re
import os
import sys
import json
from PyQt6.QtCore import Qt, QEasingCurve, QUrl
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QWidget, QVBoxLayout
from qfluentwidgets import (
    SingleDirectionScrollArea,
    SmoothScrollArea,
    ToolTipFilter,
    PixmapLabel,
    ScrollArea,
    ImageLabel,
    HorizontalPipsPager,
    PipsScrollButtonDisplayMode,
    VerticalPipsPager,
)
from qframelesswindow.webengine import FramelessWebEngineView


from .base_gallery_view import GalleryInterface
from .common.translator import Translator


class DemoStockChatView(GalleryInterface):
    """Scroll interface"""

    def __init__(self, parent=None):
        t = Translator()
        super().__init__(
            title=t.scroll, subtitle="qfluentwidgets.components.widgets", parent=parent
        )
        self.setObjectName("demoStockChatView")

        card = self.addViewCard(self.tr("Smooth scroll area"), self.buildWebEngine())
        card.card.installEventFilter(ToolTipFilter(card.card, showDelay=500))
        card.card.setToolTip(self.tr("Chitanda Eru is too hot 🥵"))
        card.card.setToolTipDuration(2000)

    def buildWebEngine(self):
        self.baseWidget = QWidget()
        self.baseWidget.setMinimumSize(600, 800)
        self.webView = FramelessWebEngineView(self)

        current_dir = os.path.dirname(os.path.abspath(__file__)) + "\\common\\html\\"
        local_file_path = os.path.join(current_dir, "base_chat_demo.html")
        self.webView.load(QUrl.fromLocalFile(local_file_path))
        self.webView.loadFinished.connect(self.on_load_finished)

        webBoxLayout = QVBoxLayout(self)
        webBoxLayout.setContentsMargins(0, 48, 0, 0)
        webBoxLayout.addWidget(self.webView)
        self.baseWidget.setLayout(webBoxLayout)
        return self.baseWidget

    def getChatData(self):
        current_dir = os.path.dirname(os.path.abspath(__file__)) + "\\common\\html\\"
        local_file_path = os.path.join(current_dir, "base_chat_demo.json")

        json_data = ""
        with open(local_file_path, "r") as file:
            json_data = json.load(file)

        source_data = [
            ["月份", "M-5", "M-4", "M-3", "M-2", "M-1", "M", "M+1"],
            ["国盛金控", 56.5, 82.1, 88.7, 70.1, 53.4, 85.1, 41.2],
            ["风华高科", 51.1, 51.4, 55.1, 53.3, 73.8, 68.7, 41.2],
            ["海信家电", 40.1, 62.2, 69.5, 36.4, 45.2, 32.5, 41.2],
            ["永辉超市", 25.2, 37.1, 41.2, 18, 33.9, 49.1, 41.2],
        ]

        json_data["dataset"]["source"] = source_data
        return json.dumps(json_data, ensure_ascii=False, indent=4)

    def on_load_finished(self):
        # 页面加载完成后，调用 JavaScript 的 setData 函数
        js_code = f"setData({self.getChatData()});"
        # AntLogger.info(f"{js_code}")
        self.webView.page().runJavaScript(js_code, self.js_callback)

    def js_callback(self, result):
        AntLogger.info(f"前端操作加载完成[Demo_Chat]: {result}")
